package com.xyh.transaction.utils;

import com.meilisearch.sdk.Client;
import com.meilisearch.sdk.Config;
import com.meilisearch.sdk.Index;
import com.meilisearch.sdk.SearchRequest;
import com.meilisearch.sdk.exceptions.MeilisearchException;
import com.meilisearch.sdk.model.SearchResult;
import com.meilisearch.sdk.model.Searchable;
import com.meilisearch.sdk.model.TaskInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

@Component
public class MeiliSearchUtil {

    @Value("${meilisearch.hostUrl}")
    private String HOST_URL;

    @Value("${meilisearch.apiKey}")
    private String API_KEY;

    /**
     * 创建索引
     *
     * @param indexName 索引名称
     * @return 创建的索引对象
     */
    public Index createIndex(String indexName) throws MeilisearchException {
        Client client = new Client(new Config(HOST_URL, API_KEY));
        return client.index(indexName);
    }

    /**
     * 获取索引
     *
     * @param indexName 索引名称
     * @return 索引对象
     */
    public Index index(String indexName) throws MeilisearchException {
        Client client = new Client(new Config(HOST_URL, API_KEY));
        return client.index(indexName);
    }

    /**
     * 添加文档到索引
     *
     * @param indexName  索引名称
     * @param primaryKey 主键字段名称
     * @param document   文档对象
     * @return 添加文档的响应
     * @throws MeilisearchException 当添加文档失败时抛出 MeilisearchException
     */
    public TaskInfo addDocument(String indexName, String primaryKey, String document) throws MeilisearchException {
        Client client = new Client(new Config(HOST_URL, API_KEY));

        // 创建索引并指定主键字段
        client.createIndex(indexName, primaryKey);

        // 获取索引对象
        Index index = client.index(indexName);

        // 添加文档到索引
        return index.addDocuments(document);
    }

    /**
     * 搜索文档
     *
     * @param indexName 索引名称
     * @param query     查询字符串
     * @return 搜索结果
     */
    public SearchResult search(String indexName, String query) throws MeilisearchException {
        Client client = new Client(new Config(HOST_URL, API_KEY));
        Index index = client.index(indexName);
        return index.search(query);
    }

    public Searchable searchByGoodsAttribute(String indexName, String searchTxt) throws MeilisearchException {
        Client client = new Client(new Config(HOST_URL, API_KEY));
        Index index = client.index(indexName);
        SearchRequest searchRequest = SearchRequest.builder()
                .q(searchTxt)
                .attributesToRetrieve(new String[]{"name", "id", "createBy", "price", "categoryName", "sellerName"}) // 返回的属性
                .attributesToSearchOn(new String[]{"name", "price", "categoryName", "sellerName"}) // 检索的属性
                .build();
        return index.search(searchRequest);
    }

    /**
     * 删除索引以及索引的下的文件
     *
     * @param indexName 索引名称
     */
    public void deleteIndexAndDocuments(String indexName) throws MeilisearchException {
        Client client = new Client(new Config(HOST_URL, API_KEY));
        client.getIndex(indexName).deleteAllDocuments();
        client.deleteIndex(indexName);
    }

    /**
     * 获取所有索引
     *
     * @return 索引列表
     */
    public List<Index> getAllIndexes() throws MeilisearchException {
        Client client = new Client(new Config(HOST_URL, API_KEY));
        return Arrays.asList(client.getIndexes().getResults());
    }

    public static void main(String[] args) {
        MeiliSearchUtil meiliSearchUtil = new MeiliSearchUtil();
        try {
            File file = new File("C:\\Users\\xiaoyh\\Downloads\\movies.json");
            if (!file.exists()) {
                throw new RuntimeException("文件不存在");
            }

            // 读取整个文件为字符串
            String jsonData = new String(Files.readAllBytes(Paths.get(file.getPath())));

            meiliSearchUtil.addDocument("movies","id",jsonData);
        } catch (Exception e){
            System.out.println("上传meilisearch失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    public void deleteDocument(String indexName, Integer[] deleteIds) throws MeilisearchException {
        Client client = new Client(new Config(HOST_URL, API_KEY));
        for (Integer id : deleteIds) {
            client.index(indexName).deleteDocument(String.valueOf(id));
        }
    }
}
